from django.shortcuts import render
import string
import random
from datetime import timedelta
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from django.core.cache import cache
from django.core.signing import Signer
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from .models import User, Author, BlogPost,Student,course
# Create your views here.
# asdfghjkl

@api_view(['POST'])
def addcourse(request):
    data = JSONParser().parse(request)
    classname = data.get('classname')
    classtime = data.get('classtime')
    stuid = data.get('stuid')

    sutobj = Student.objects.get(id=stuid)


    course(classname=classname,classtime=classtime).save()
    classobj = course.objects.get(classname=classname)

    classobj.student.add(sutobj)
    # classobj.student.a
    return JsonResponse({
        'mag': '添加成功'
    })


@api_view(['GET'])
def getstudentcourse1(request):
    name = request.GET.get('name')

    stuobj = course.objects.get(classname=name)
    l = []
    for i in stuobj.student.all():
        l.append({
            'stuname':i.name,
            'age':i.age,
        })
    return JsonResponse({
        'msg':'查询成功',
        'classname':stuobj.classname,
        'time':stuobj.classtime,
        'data':l
    })


@api_view(['GET'])
def getstudentcourse(request):
    name = request.GET.get('name')

    stuobj = Student.objects.get(name=name)
    l = []
    for i in stuobj.course.all():
        l.append({
            'coursename':i.classname,
            'classtime':i.classtime,
        })
    return JsonResponse({
        'msg':'查询成功',
        'stuname':stuobj.name,
        'age':stuobj.age,
        'data':l
    })







# vue 注册（添加用户）
@api_view(['POST'])
def adduser(request):
    data = JSONParser().parse(request)
    username = data.get('username')
    password = data.get('password')

    User(username=username, password=password).save()
    return JsonResponse({
        'msg': "添加成功"
    })








# 判断是否为空
def is_empty(c):
    return c is None or str(c).strip() == ''

# 生成token
def createdtoken(name):
    r = set()

    randomstr = ''.join(random.choices(string.ascii_letters, k=8))
    token = Signer().sign(randomstr+name)
    cache.set(f'test_{name}', token, timeout=timedelta(minutes=100).total_seconds())
    return token

# 鉴权
def checktoken(request):
    gettoken = request.META.get('HTTP_TOKEN')
    if gettoken is None:
        return False,'xxx'
    untoken = Signer().unsign(gettoken)
    name = untoken[8: ]
    checktoken = cache.get(f'test_{name}')
    if checktoken is None:
        return False, 'xxx'
    return True, 'xxx'
#
# # 添加用户
# @api_view(['POST'])
# def adduser(request):
#     data = JSONParser().parse(request)
#     username = data.get('username')
#     password = data.get('password')
#     if is_empty(username) or is_empty(password):
#         return JsonResponse({
#             'msg': "字段不能为空"
#         }, status=400)
#     if User.objects.filter(username=username).exists() is False:
#         return JsonResponse({
#             'msg': "用户名已存在"
#         }, status=400)
#     User(username=username, password=password).save()
#     return JsonResponse({
#         'msg': "注册成功"
#     })
#
# # 登录
# @api_view(['GET'])
# def login(request):
#     username = request.GET.get('username')
#     password = request.GET.get('password')
#     if is_empty(username) or is_empty(password):
#         return JsonResponse({
#             'msg': "字段不能为空"
#         }, status=400)
#     if User.objects.filter(username=username).exists() is False:
#         return JsonResponse({
#             'msg': "用户名不存在"
#         }, status=400)
#     obj = User.objects.get(username=username)
#     if obj.password != password:
#         return JsonResponse({
#             'msg': "密码错误"
#         }, status=400)
#     return JsonResponse({
#         'msg': "登录成功",
#         'token': createdtoken(username)
#     })
